package com.ztom.top100;

/**
 * 除自身以外数组的乘积
 * <p>
 * https://leetcode-cn.com/problems/product-of-array-except-self/
 *
 * @author ZhangTao
 */
public class Code68ProductExceptSelf {

    public int[] productExceptSelf1(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return null;
        }
        // 左右遍历两遍, 分别记录左右两遍的乘积
        int[] l = new int[nums.length];
        int[] r = new int[nums.length];
        int[] res = new int[nums.length];

        int tmp = 1;
        for (int i = 0; i < nums.length; i++) {
            l[i] = tmp;
            tmp *= nums[i];
        }
        tmp = 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            r[i] = tmp;
            tmp *= nums[i];
        }

        for (int i = 0; i < nums.length; i++) {
            res[i] = l[i] * r[i];
        }

        return res;
    }

    /**
     * 压缩空间
     *
     * @param nums
     * @return
     */
    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return null;
        }
        int[] res = new int[nums.length];
        int tmp = 1;
        for (int i = 0; i < nums.length; i++) {
            res[i] = tmp;
            tmp *= nums[i];
        }
        tmp = 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            res[i] *= tmp;
            tmp *= nums[i];
        }

        return res;
    }
}
